package com.zzyl.job;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.zzyl.constant.CacheConstants;
import com.zzyl.entity.AlertRule;
import com.zzyl.mapper.AlertRuleMapper;
import com.zzyl.service.AlertRuleService;
import com.zzyl.vo.DeviceDataVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Component
@Slf4j
public class AlertJob {

    @Autowired
    AlertRuleMapper alertRuleMapper;
    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    AlertRuleService alertRuleService;


    //每隔5秒钟执行一次 的cron表达式
    @Scheduled(cron = "0/5 * * * * ?")
    public void task() {
        //开始
        log.info("开始执行定时任务,准备校验数据........");
        //查询所有的规则
        List<AlertRule> alertRules = alertRuleMapper.selectByFunctionId(null, null, null);

        //规则判断是否为空
        if (alertRules == null || alertRules.size() == 0) {
            return;
        }

        //查询所有的设备上报的数据
        List<Object> jsonList = redisTemplate.opsForHash().values(CacheConstants.DEVICE_LASTDATA_CACHEKEY);
        //规则判断是否为空
        if (jsonList == null || jsonList.size() == 0) {
            return;
        }

        //遍历设备上报的数据
        List<DeviceDataVo> deviceDataVoList=new ArrayList<>();
        jsonList.forEach(json -> {
            List<DeviceDataVo> list = JSONUtil.toList(json.toString(), DeviceDataVo.class);
            deviceDataVoList.addAll(list);
        });

        log.info("设备上报的数据：总共：{} 条",deviceDataVoList.size() );
            //数据太多，需要遍历出来，一条条的处理
        for (DeviceDataVo deviceDataVo : deviceDataVoList) {

            alertRuleService.alertFilter(deviceDataVo);

        }
        //结束
    }
}
